package com.dqhl.business.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.business.Base.BaseActivity;
import com.dqhl.business.R;
import com.dqhl.business.modle.Community;
import com.dqhl.business.modle.GoodsClass;
import com.dqhl.business.modle.Residence;
import com.dqhl.business.modle.ShopInfo;
import com.dqhl.business.util.Config;
import com.dqhl.business.util.Constant;
import com.dqhl.business.util.Dlog;
import com.dqhl.business.util.JsonUtils;
import com.dqhl.business.view.GoodsClassPopupWindow;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description: 店铺设置
 * autour: guanluocang
 * date: 2016/11/6 17:04
 */
public class ShopSettingActivity extends BaseActivity implements View.OnClickListener {

    private Context context;
    private ImageView iv_goodsGoBack;
    private EditText et_shopName;//店铺名称
    private LinearLayout ll_aptitude;//资质认证

    //    private LinearLayout ll_shop_time;//配送时间
    private LinearLayout ll_shop_around;//服务范围
    private EditText et_contactName;//联系人姓名
    private EditText et_contactTel;//联系电话
    private EditText et_contactAddress;//营业地址
    //    private ShopSettingPopwindow shopTypePopWindow;
    private GoodsClassPopupWindow shopTypePopupWindow;
    private TextView tv_shopType;//经营类目
    private TextView tv_goodsTopTitle;
    private TextView tv_topRight;
    private TextView tv_start_time;
    private TextView tv_stop_time;
    //时间选择器
//    TimePickerDialog mDialogMonthDayHourMinute;
    TimePickerDialog mDialogAll;
    SimpleDateFormat sf = new SimpleDateFormat("HH:mm");

    private ShopInfo shopInfo; //商户信息
    private GoodsClass goodsClass; //商品类型,经验类目
    private List<GoodsClass> goodsClassList; //经验类目列表
//    private List<Residence> residenceList; //服务范围

    private String shopTypeId; //分类的ID
    private String startTime;
    private String stopTime;
    private List<String> picList;
    private String strResidence;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_setting);
        context = this;
        initView();

        initData();
        TimePicker();
        registerBroadcastReceiver();
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_UPDATE_PIC)) {
                initData();
            } else if (action.equals(Constant.ACTION_UPDATE_RANGE)) {
                initData();
            }
        }
    };

    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_UPDATE_PIC);
        intentFilter.addAction(Constant.ACTION_UPDATE_RANGE);
        registerReceiver(receiver, intentFilter);
    }

    private void initView() {
        et_shopName = (EditText) findViewById(R.id.et_shopName);
        ll_aptitude = (LinearLayout) findViewById(R.id.ll_aptitude);
        ll_shop_around = (LinearLayout) findViewById(R.id.ll_shop_around);
        et_contactName = (EditText) findViewById(R.id.et_contactName);
        et_contactTel = (EditText) findViewById(R.id.et_contactTel);
        et_contactAddress = (EditText) findViewById(R.id.et_contactAddress);
        tv_shopType = (TextView) findViewById(R.id.tv_shopType);
        tv_goodsTopTitle = (TextView) findViewById(R.id.tv_goodsTopTitle);
        tv_goodsTopTitle.setText("店铺设置");
        iv_goodsGoBack = (ImageView) findViewById(R.id.iv_goodsGoBack);
        tv_topRight = (TextView) findViewById(R.id.tv_topRight);
        tv_topRight.setText("保存");
        tv_topRight.setVisibility(View.VISIBLE);
        tv_topRight.setTextColor(ContextCompat.getColor(this, R.color.daiqianshou));

        tv_start_time = (TextView) findViewById(R.id.tv_start_time);
        tv_stop_time = (TextView) findViewById(R.id.tv_stop_time);

        tv_shopType.setOnClickListener(this);
        iv_goodsGoBack.setOnClickListener(this);
        ll_shop_around.setOnClickListener(this);
        ll_aptitude.setOnClickListener(this);
        tv_topRight.setOnClickListener(this);
        tv_start_time.setOnClickListener(this);
        tv_stop_time.setOnClickListener(this);
    }

    private void initData() {
        showCustomLoadBar(".");
        RequestParams params = new RequestParams(Config.personal_shop_info);
        params.addBodyParameter("mobile_phone", user.getMobile_phone());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                if (0 == errCode) {
                    String strShopInfo = JsonUtils.getInfo(data, "userinfo");
                    String strClass = JsonUtils.getInfo(data, "class");
                    strResidence = JsonUtils.getInfo(data, "residence");

                    shopInfo = JSON.parseObject(strShopInfo, ShopInfo.class);

                    et_shopName.setText(shopInfo.getName());
                    et_contactName.setText(shopInfo.getShopkeeper());
                    et_contactTel.setText(shopInfo.getTelephone());
                    et_contactAddress.setText(shopInfo.getAddress());
                    startTime = shopInfo.getSeller_open();
                    stopTime = shopInfo.getSeller_close();
                    tv_start_time.setText(shopInfo.getSeller_open());
                    tv_stop_time.setText(shopInfo.getSeller_close());

                    if (!TextUtils.isEmpty(strClass)) {
                        goodsClass = JSON.parseObject(strClass, GoodsClass.class);

                        shopTypeId = goodsClass.getId();
                        tv_shopType.setText(goodsClass.getName());
                    } else {
                        shopTypeId = "";
                        tv_shopType.setText("请选择类目");
                    }

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_goodsGoBack:
                finish();
                break;
            case R.id.ll_aptitude:
                Bundle bundle1 = new Bundle();
                bundle1.putSerializable("shopInfo", shopInfo);
                bundle1.putSerializable("goodsClass", goodsClass);
                overlay(ShopAptitudeActivity.class, bundle1);
                break;
            case R.id.tv_shopType:
                showShopTypePopupWindow();
                break;
            case R.id.tv_start_time: //选择开始时间
                showStartTimeSelect();
                break;
            case R.id.tv_stop_time: //结束时间
                showStopTimeSelect();
                break;
            case R.id.ll_shop_around:
                Bundle bundle = new Bundle();
                bundle.putString("residence", strResidence);
                overlay(ServiceAroundActivity.class, bundle);
                break;
            case R.id.tv_topRight:
                doSave();
                break;
        }
    }

    private void showStartTimeSelect() {
        TimePickerDialog startTimeDialog = new TimePickerDialog.Builder()
                .setType(Type.HOURS_MINS)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        String text = getDateToString(millseconds);
                        startTime = text;
                        tv_start_time.setText(text);
                    }
                })
                .build();
        startTimeDialog.show(getSupportFragmentManager(), "start_hour_minute");
    }

    private void showStopTimeSelect() {
        TimePickerDialog stopTimeDialog = new TimePickerDialog.Builder()
                .setType(Type.HOURS_MINS)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        String text = getDateToString(millseconds);
                        stopTime = text;
                        tv_stop_time.setText(text);
                    }
                })
                .build();
        stopTimeDialog.show(getSupportFragmentManager(), "stop_hour_minute");
    }

    /**
     * 保存
     */
    private void doSave() {
        String name = et_shopName.getText().toString();
        String shopkeeper = et_contactName.getText().toString();
        String address = et_contactAddress.getText().toString();
        String telephone = et_contactTel.getText().toString();
        Dlog.e(user.getUser_id() + ";" + name + ";" + shopTypeId + ";" + shopkeeper + ";" + address
                + ";" + telephone + ";" + startTime + ";" + stopTime);
        if (TextUtils.isEmpty(name)) {
            toast("请填写店铺名");
        } else if (TextUtils.isEmpty(shopTypeId)) {
            toast("请选择经营类目");
        } else if (TextUtils.isEmpty(shopkeeper)) {
            toast("请填写联系人");
        } else if (TextUtils.isEmpty(telephone)) {
            toast("请填写联系电话");
        } else if (TextUtils.isEmpty(address)) {
            toast("请填写营业地址");
        } else if (TextUtils.isEmpty(startTime)) {
            toast("请选择配送时间");
        } else if (TextUtils.isEmpty(stopTime)) {
            toast("请选择配送时间");
        } else {
            showCustomLoadBar(".");
            RequestParams params = new RequestParams(Config.personal_shop_info_modify);
            params.addBodyParameter("user_id", user.getUser_id());
            params.addBodyParameter("name", name);
            params.addBodyParameter("class_id", shopTypeId);
            params.addBodyParameter("shopkeeper", shopkeeper);
            params.addBodyParameter("address", address);
            params.addBodyParameter("telephone", telephone);
            params.addBodyParameter("seller_open", startTime);
            params.addBodyParameter("seller_close", stopTime);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e(result);
                    int errCode = JsonUtils.getErrCode(result);
                    String errMsg = JsonUtils.getErrMsg(result);
                    if (0 == errCode) {
                        toast("修改成功");
                        finish();
                    } else {
                        toast(errMsg);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });
        }
    }

    private void showShopTypePopupWindow() {
        showCustomLoadBar(".");
        RequestParams params = new RequestParams(Config.personal_shop_type);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                if (0 == errCode) {
                    String seller_class = JsonUtils.getInfo(data, "seller_class");
                    goodsClassList = JSON.parseArray(seller_class, GoodsClass.class);
                    shopTypePopupWindow = new GoodsClassPopupWindow(context, goodsClassList,
                            new GoodsClassPopupWindow.IOnItemSelectListener() {
                                @Override
                                public void onItemClick(int position) {
                                    shopTypeId = goodsClassList.get(position).getId();
                                    tv_shopType.setText(goodsClassList.get(position).getName());
                                }
                            });
                    shopTypePopupWindow.setWidth(tv_shopType.getWidth());
                    shopTypePopupWindow.showAsDropDown(tv_shopType);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }

    //时间选择器
    public void TimePicker() {
        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
        mDialogAll = new com.jzxiang.pickerview.TimePickerDialog.Builder()
                .setCancelStringId("Cancel")
                .setSureStringId("Sure")
                .setTitleStringId("TimePicker")
                .setYearText("Year")
                .setMonthText("Month")
                .setDayText("Day")
                .setHourText("Hour")
                .setMinuteText("Minute")
                .setCyclic(false)
                .setMinMillseconds(System.currentTimeMillis())
                .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                .setType(Type.ALL)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.timepicker_toolbar_bg))
                .setWheelItemTextSize(12)
                .build();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}
